import React, { useState, useEffect, useRef } from 'react';
import styles from '../component/Course.module.css';
import {
    Card,
    Table,
    Button,
    Input,
    DatePicker,
    Switch,
    Typography,
    Select,
    Modal,
    Form,
    Upload,
    message,
    Progress,
    Space,
    Image,
    Tag,
    Popconfirm,
    Row,
    Col,
    Divider,
    Alert,
    Tooltip
} from 'antd';
import {
    FilterOutlined,
    LeftOutlined,
    RightOutlined,
    PlusOutlined,
    UploadOutlined,
    DeleteOutlined,
    EyeOutlined,
    PlayCircleOutlined,
    FileImageOutlined,
    VideoCameraOutlined,
    CloudUploadOutlined,
    FileTextOutlined,
    FilePptOutlined,
    FileWordOutlined,
    FilePdfOutlined,
    FileExcelOutlined,
    RobotOutlined
} from '@ant-design/icons';
import { ActionPermissionGuard } from './PermissionGuard';

const { Search } = Input;
const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

export default function Course() {
    const [courses, setCourses] = useState([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [searchText, setSearchText] = useState('');
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [uploading, setUploading] = useState(false);
    const [form] = Form.useForm();

    // 表单数据
    const [formValues, setFormValues] = useState({
        name: '',
        description: '',
        price: 0,
        coverImageUrl: '',
        videoUrls: [],
        fileUrls: [],
        imageUrls: [],
        teacherId: '',
        teacherName: ''
    });

    // 上传文件状态
    const [uploadedVideos, setUploadedVideos] = useState([]);
    const [uploadedFiles, setUploadedFiles] = useState([]);
    const [uploadedImages, setUploadedImages] = useState([]);
    const [coverImages, setCoverImages] = useState([]);
    
    // 分片上传配置和状态
    const CHUNK_SIZE = 2 * 1024 * 1024; // 2MB 分片大小
    const MAX_FILE_SIZE = 500 * 1024 * 1024; // 500MB 最大文件大小
    const [chunkUploadProgress, setChunkUploadProgress] = useState({});
    const [uploadingFiles, setUploadingFiles] = useState([]);

    // 获取课程列表
    const fetchCourses = async (page = 1, search = '') => {
        setLoading(true);
        try {
            // 检查用户是否已登录
            const currentUser = localStorage.getItem('currentUser');
            if (!currentUser) {
                console.error('用户未登录');
                return;
            }
            
            const token = localStorage.getItem('token');
            const response = await fetch(`http://localhost:3001/api/courses?page=${page}&limit=${pagination.pageSize}&search=${search}`, {
                headers: {
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                }
            });
            
            if (!response.ok) {
                if (response.status === 401) {
                    console.error('获取课程列表失败: 认证失败');
                    message.error('认证失败，请重新登录');
                    return;
                }
                throw new Error('获取课程列表失败');
            }
            
            const result = await response.json();
            if (result.success) {
                console.log('获取到的课程数据:', result.data);
                // 检查每个课程的coverImageUrls字段
                result.data.forEach((course, index) => {
                    console.log(`课程 ${index + 1} (${course.name}):`, {
                        coverImageUrls: course.coverImageUrls,
                        hasCoverImages: course.coverImageUrls && course.coverImageUrls.length > 0,
                        coverImageUrlsType: typeof course.coverImageUrls,
                        coverImageUrlsLength: course.coverImageUrls ? course.coverImageUrls.length : 0
                    });
                });
                setCourses(result.data);
                setPagination({
                    ...pagination,
                    current: result.pagination.current,
                    total: result.pagination.total
                });
            } else {
                message.error(result.message || '获取课程列表失败');
            }
        } catch (error) {
            console.error('获取课程列表错误:', error);
            message.error('获取课程列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取教师列表
    const [teachers, setTeachers] = useState([]);
    const fetchTeachers = async () => {
        try {
            // 检查用户是否已登录
            const currentUser = localStorage.getItem('currentUser');
            if (!currentUser) {
                console.error('用户未登录');
                return;
            }
            
            const token = localStorage.getItem('token');
            const response = await fetch('http://localhost:3001/api/teachers', {
                headers: {
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                }
            });
            
            if (!response.ok) {
                if (response.status === 401) {
                    console.error('获取教师列表失败: 认证失败');
                    message.error('认证失败，请重新登录');
                    return;
                }
                throw new Error('获取教师列表失败');
            }
            
            const result = await response.json();
            if (result.success) {
                setTeachers(result.data);
            } else {
                console.error('获取教师列表失败:', result.message);
            }
        } catch (error) {
            console.error('获取教师列表错误:', error);
        }
    };

    useEffect(() => {
        fetchCourses();
        fetchTeachers();
    }, []);

    // 生成文件唯一标识
    const generateFileId = (file) => {
        return `${file.name}-${file.size}-${file.lastModified}`;
    };

    // 分片上传文件
    const uploadFileInChunks = async (file, onProgress) => {
        const fileId = generateFileId(file);
        const chunks = Math.ceil(file.size / CHUNK_SIZE);
        const uploadedChunks = new Set();
        
        setChunkUploadProgress(prev => ({
            ...prev,
            [fileId]: { current: 0, total: chunks, percentage: 0 }
        }));

        try {
            // 1. 初始化上传
            const token = localStorage.getItem('token');
            const initResponse = await fetch('http://localhost:3001/api/upload/init', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                },
                body: JSON.stringify({
                    fileName: file.name,
                    fileSize: file.size,
                    fileType: file.type,
                    chunks: chunks
                })
            });

            if (!initResponse.ok) {
                throw new Error('初始化上传失败');
            }

            const initResult = await initResponse.json();
            if (!initResult.success) {
                throw new Error(initResult.message || '初始化上传失败');
            }

            // 2. 上传分片
            for (let chunkIndex = 0; chunkIndex < chunks; chunkIndex++) {
                const start = chunkIndex * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);

                const formData = new FormData();
                formData.append('chunk', chunk);
                formData.append('chunkIndex', chunkIndex);
                formData.append('fileId', fileId);
                formData.append('fileName', file.name);

                const chunkResponse = await fetch('http://localhost:3001/api/upload/chunk', {
                    method: 'POST',
                    headers: {
                        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                    },
                    body: formData
                });

                if (!chunkResponse.ok) {
                    throw new Error(`分片 ${chunkIndex + 1} 上传失败`);
                }

                const chunkResult = await chunkResponse.json();
                if (!chunkResult.success) {
                    throw new Error(chunkResult.message || `分片 ${chunkIndex + 1} 上传失败`);
                }

                uploadedChunks.add(chunkIndex);
                
                // 更新进度
                const percentage = Math.round(((chunkIndex + 1) / chunks) * 100);
                setChunkUploadProgress(prev => ({
                    ...prev,
                    [fileId]: { 
                        current: chunkIndex + 1, 
                        total: chunks, 
                        percentage 
                    }
                }));

                if (onProgress) {
                    onProgress(percentage);
                }
            }

            // 3. 完成上传
            const completeResponse = await fetch('http://localhost:3001/api/upload/complete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                },
                body: JSON.stringify({
                    fileId: fileId,
                    fileName: file.name
                })
            });

            if (!completeResponse.ok) {
                throw new Error('完成上传失败');
            }

            const completeResult = await completeResponse.json();
            if (!completeResult.success) {
                throw new Error(completeResult.message || '完成上传失败');
            }

            return completeResult.data;

        } catch (error) {
            console.error('分片上传错误:', error);
            throw error;
        } finally {
            // 清理进度状态
            setChunkUploadProgress(prev => {
                const newState = { ...prev };
                delete newState[fileId];
                return newState;
            });
        }
    };

    // 获取文件类型和图标
    const getFileTypeInfo = (file) => {
        const fileName = file.name.toLowerCase();
        const fileType = file.type.toLowerCase();
        
        if (fileType.startsWith('video/')) {
            return { type: 'video', icon: <VideoCameraOutlined />, category: '视频' };
        } else if (fileName.endsWith('.ppt') || fileName.endsWith('.pptx') || fileType.includes('presentation')) {
            return { type: 'document', icon: <FilePptOutlined />, category: 'PPT文档' };
        } else if (fileName.endsWith('.doc') || fileName.endsWith('.docx') || fileType.includes('document')) {
            return { type: 'document', icon: <FileWordOutlined />, category: 'Word文档' };
        } else if (fileName.endsWith('.pdf') || fileType.includes('pdf')) {
            return { type: 'document', icon: <FilePdfOutlined />, category: 'PDF文档' };
        } else if (fileName.endsWith('.xls') || fileName.endsWith('.xlsx') || fileType.includes('spreadsheet')) {
            return { type: 'document', icon: <FileExcelOutlined />, category: 'Excel文档' };
        } else if (fileName.endsWith('.txt') || fileType.includes('text')) {
            return { type: 'document', icon: <FileTextOutlined />, category: '文本文档' };
        } else {
            return { type: 'document', icon: <FileTextOutlined />, category: '其他文档' };
        }
    };

    // 处理大文件上传（视频和文档）
    const handleLargeFileUpload = async (file, type = 'auto') => {
        const fileInfo = getFileTypeInfo(file);
        const actualType = type === 'auto' ? fileInfo.type : type;
        if (file.size > MAX_FILE_SIZE) {
            message.error(`文件大小不能超过 ${MAX_FILE_SIZE / 1024 / 1024}MB`);
            return null;
        }

        setUploading(true);
        setUploadingFiles(prev => [...prev, file.name]);

        try {
            const result = await uploadFileInChunks(file, (progress) => {
                setUploadProgress(progress);
            });

            message.success(`${file.name} 上传成功`);
            
            const fileData = {
                url: result.url,
                originalName: file.name,
                filename: result.filename,
                type: fileInfo.type,
                category: fileInfo.category,
                icon: fileInfo.icon
            };

            if (actualType === 'video') {
                setUploadedVideos(prev => [...prev, fileData]);
                setFormValues(prev => ({
                    ...prev,
                    videoUrls: [...prev.videoUrls, result.url]
                }));
            } else if (actualType === 'document') {
                setUploadedFiles(prev => [...prev, fileData]);
                setFormValues(prev => ({
                    ...prev,
                    fileUrls: [...(prev.fileUrls || []), result.url]
                }));
            } else if (actualType === 'image') {
                setUploadedImages(prev => [...prev, result.url]);
                setFormValues(prev => ({
                    ...prev,
                    imageUrls: [...prev.imageUrls, result.url]
                }));
            }

            return result.url;

        } catch (error) {
            console.error('大文件上传错误:', error);
            message.error(`${file.name} 上传失败: ${error.message}`);
            return null;
        } finally {
            setUploading(false);
            setUploadProgress(0);
            setUploadingFiles(prev => prev.filter(name => name !== file.name));
        }
    };

    // 上传文件（支持视频和文档，支持大文件和拖拽上传）
    const handleFileUpload = async (file) => {
        const fileInfo = getFileTypeInfo(file);
        
        // 检查文件类型是否支持
        const supportedTypes = ['video', 'document'];
        if (!supportedTypes.includes(fileInfo.type)) {
            message.error('只支持上传视频文件和文档文件（PPT、Word、PDF、Excel、TXT等）');
            return false;
        }

        // 对于大文件使用分片上传
        if (file.size > 10 * 1024 * 1024) { // 10MB以上使用分片上传
            await handleLargeFileUpload(file, 'auto');
        } else {
            // 小文件使用普通上传
            const formData = new FormData();
            const fieldName = fileInfo.type === 'video' ? 'video' : 'file';
            formData.append(fieldName, file);

            setUploading(true);
            setUploadProgress(0);

            try {
                const apiEndpoint = fileInfo.type === 'video' 
                    ? 'http://localhost:3001/api/upload-course-video'
                    : 'http://localhost:3001/api/upload-course-file';
                    
                const token = localStorage.getItem('token');
                const response = await fetch(apiEndpoint, {
                    method: 'POST',
                    headers: {
                        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                    },
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`${fileInfo.category}上传失败`);
                }

                const result = await response.json();
                if (result.success) {
                    message.success(`${fileInfo.category}上传成功`);
                    
                    const fileData = {
                        ...result.data,
                        type: fileInfo.type,
                        category: fileInfo.category,
                        icon: fileInfo.icon,
                        originalName: file.name
                    };

                    if (fileInfo.type === 'video') {
                        setUploadedVideos(prev => [...prev, fileData]);
                        setFormValues(prev => ({
                            ...prev,
                            videoUrls: [...prev.videoUrls, result.data.url]
                        }));
                    } else {
                        setUploadedFiles(prev => [...prev, fileData]);
                        setFormValues(prev => ({
                            ...prev,
                            fileUrls: [...(prev.fileUrls || []), result.data.url]
                        }));
                    }
                    
                    return result.data.url;
                } else {
                    message.error(result.message || `${fileInfo.category}上传失败`);
                    return null;
                }
            } catch (error) {
                console.error(`${fileInfo.category}上传错误:`, error);
                message.error(`${fileInfo.category}上传失败`);
                return null;
            } finally {
                setUploading(false);
                setUploadProgress(0);
            }
        }

        return false; // 阻止默认上传行为
    };

    // 上传图片文件
    const handleImageUpload = async (files) => {
        const formData = new FormData();
        files.forEach(file => {
            formData.append('images', file);
        });

        setUploading(true);
        setUploadProgress(0);

        try {
            const token = localStorage.getItem('token');
            const response = await fetch('http://localhost:3001/api/upload-course-images', {
                method: 'POST',
                headers: {
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                },
                body: formData
            });

            if (!response.ok) {
                throw new Error('图片上传失败');
            }

            const result = await response.json();
            if (result.success) {
                message.success(`成功上传 ${result.data.count} 张图片`);
                setUploadedImages(prev => [...prev, ...result.data.urls]);
                setFormValues(prev => ({
                    ...prev,
                    imageUrls: [...prev.imageUrls, ...result.data.urls]
                }));
                return result.data.urls;
            } else {
                message.error(result.message || '图片上传失败');
                return [];
            }
        } catch (error) {
            console.error('图片上传错误:', error);
            message.error('图片上传失败');
            return [];
        } finally {
            setUploading(false);
            setUploadProgress(0);
        }
    };

    // 上传封面图片（支持分片上传和拖拽上传）
    const handleCoverImageUpload = async (file) => {
        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            message.error('只能上传图片文件');
            return false;
        }

        // 检查文件大小
        if (file.size > 10 * 1024 * 1024) { // 10MB限制
            message.error('封面图片不能超过 10MB');
            return false;
        }

        // 对于大图片使用分片上传
        if (file.size > 2 * 1024 * 1024) { // 2MB以上使用分片上传
            const url = await handleLargeFileUpload(file, 'image');
            if (url) {
                setCoverImages(prev => [...prev, { url, originalName: file.name }]);
                setFormValues(prev => ({
                    ...prev,
                    coverImageUrls: [...(prev.coverImageUrls || []), url]
                }));
            }
        } else {
            // 小图片使用普通上传
            const formData = new FormData();
            formData.append('images', file);

            try {
                const token = localStorage.getItem('token');
                const response = await fetch('http://localhost:3001/api/upload-course-images', {
                    method: 'POST',
                    headers: {
                        'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
                    },
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('封面图片上传失败');
                }

                const result = await response.json();
                if (result.success && result.data.urls.length > 0) {
                    message.success('封面图片上传成功');
                    const newImage = { url: result.data.urls[0], originalName: file.name };
                    setCoverImages(prev => [...prev, newImage]);
                    setFormValues(prev => ({
                        ...prev,
                        coverImageUrls: [...(prev.coverImageUrls || []), result.data.urls[0]]
                    }));
                    return result.data.urls[0];
                } else {
                    message.error(result.message || '封面图片上传失败');
                    return null;
                }
            } catch (error) {
                console.error('封面图片上传错误:', error);
                message.error('封面图片上传失败');
                return null;
            }
        }

        return false; // 阻止默认上传行为
    };

    // 添加课程
    const handleAddCourse = async () => {
        try {
          const values = await form.validateFields();
          const currentUser = JSON.parse(localStorage.getItem('currentUser')) || { username: 'admin' };
      
          // 确保视频URL格式正确
          const processedVideoUrls = uploadedVideos.map(video => 
            video.url.startsWith('/uploads/videos/') ? video.url : `/uploads/videos/${video.filename}`
          );
      
          const courseData = {
            name: values.name,
            description: values.description,
            price: values.price,
            coverImageUrls: coverImages.map(img => img.url),
                            videoUrls: processedVideoUrls,
                fileUrls: uploadedFiles.map(file => file.url),
            imageUrls: uploadedImages,
            teacherId: values.teacherId,
            teacherName: teachers.find(t => t._id === values.teacherId)?.name || '',
            uploaderUsername: currentUser.username
          };
      
          const token = localStorage.getItem('token');
          const response = await fetch('http://localhost:3001/api/add-course', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
              'user-id': currentUser.id || ''
            },
            body: JSON.stringify(courseData)
          });
      
          const result = await response.json();
          
          if (!response.ok) {
            throw new Error(result.message || '添加课程失败');
          }
      
          if (result.success) {
            message.success('课程添加成功');
            setIsModalVisible(false);
            // 重置表单和状态
            form.resetFields();
            setFormValues({
              name: '',
              description: '',
              price: 0,
              coverImageUrls: [],
              videoUrls: [],
              imageUrls: [],
              teacherId: '',
              teacherName: ''
            });
            setUploadedVideos([]);
            setUploadedImages([]);
            setCoverImages([]);
            fetchCourses(); // 刷新课程列表
          } else {
            message.error(result.message || '添加课程失败');
          }
        } catch (error) {
          console.error('添加课程错误:', error);
          message.error(`添加课程失败: ${error.message}`);
        }
      };

    // 删除课程
    const handleDeleteCourse = async (id) => {
        try {
            // 获取当前用户信息
            const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
            
            const token = localStorage.getItem('token');
            const response = await fetch(`http://localhost:3001/api/courses/${id}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '',
                    'user-id': currentUser.id || ''
                }
            });

            if (!response.ok) {
                throw new Error('删除课程失败');
            }

            const result = await response.json();
            if (result.success) {
                message.success('课程删除成功');
                fetchCourses();
            } else {
                message.error(result.message || '删除课程失败');
            }
        } catch (error) {
            console.error('删除课程错误:', error);
            message.error('删除课程失败');
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '封面',
            dataIndex: 'coverImageUrls',
            key: 'coverImageUrls',
            width: 120,
            render: (urls) => {
                console.log('渲染封面图片，urls:', urls);
                if (!urls || urls.length === 0) {
                    console.log('没有封面图片，显示默认图片');
                    return (
                        <Image
                            width={60}
                            height={40}
                            src=""
                            style={{ objectFit: 'cover' }}
                        />
                    );
                }
                
                console.log('有封面图片，准备渲染:', urls.slice(0, 3));
                return (
                    <div style={{ display: 'flex', gap: 4 }}>
                        {urls.slice(0, 3).map((url, index) => {
                            const fullUrl = url.startsWith('http') ? url : `http://localhost:3001${url}`;
                            console.log(`图片 ${index + 1} URL:`, { original: url, full: fullUrl });
                            return (
                                <Image
                                    key={index}
                                    width={60}
                                    height={40}
                                    src={fullUrl}
                                    fallback=""
                                    style={{ objectFit: 'cover' }}
                                />
                            );
                        })}
                        {urls.length > 3 && (
                            <div style={{
                                width: 60,
                                height: 40,
                                background: '#f0f0f0',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: '12px',
                                color: '#666'
                            }}>
                                +{urls.length - 3}
                            </div>
                        )}
                    </div>
                );
            },
        },
        {
            title: '课程名称',
            dataIndex: 'name',
            key: 'name',
            width: 200,
        },
        {
            title: '讲师',
            dataIndex: 'teacherName',
            key: 'teacherName',
            width: 120,
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
            width: 100,
            render: (price) => `¥${(price / 100).toFixed(2)}`,
        },
        {
            title: '视频数量',
            dataIndex: 'videoResources',
            key: 'videoCount',
            width: 100,
            render: (videoResources) => videoResources?.length || 0,
        },
        {
            title: '图片数量',
            dataIndex: 'imageResources',
            key: 'imageCount',
            width: 100,
            render: (imageResources) => imageResources?.length || 0,
        },
        {
            title: '上传人',
            dataIndex: 'uploaderUsername',
            key: 'uploaderUsername',
            width: 120,
        },
        {
            title: '上传时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            width: 180,
            render: (date) => new Date(date).toLocaleString(),
        },
        {
            title: '操作',
            key: 'action',
            width: 200,
            render: (_, record) => {
                // 获取当前用户信息
                const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
                
                return (
                    <Space>
                        <Button 
                            type="link" 
                            size="small" 
                            icon={<EyeOutlined />}
                            onClick={() => handleViewCourse(record)}
                        >
                            查看
                        </Button>
                        <Button 
                            type="link" 
                            size="small" 
                            icon={<PlayCircleOutlined />}
                            onClick={() => handlePlayCourse(record)}
                        >
                            播放
                        </Button>
                        <ActionPermissionGuard action="delete" userId={currentUser.id}>
                            <Popconfirm
                                title="确定要删除这个课程吗？"
                                onConfirm={() => handleDeleteCourse(record._id)}
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button 
                                    type="link" 
                                    size="small" 
                                    danger
                                    icon={<DeleteOutlined />}
                                >
                                    删除
                                </Button>
                            </Popconfirm>
                        </ActionPermissionGuard>
                    </Space>
                );
            },
        },
    ];

    // 查看课程详情
    const handleViewCourse = (course) => {
        Modal.info({
            title: course.name,
            width: 800,
            content: (
                <div>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Image
                                width={200}
                                src={course.coverImageUrls && course.coverImageUrls.length > 0 
                                    ? (course.coverImageUrls[0].startsWith('http') ? course.coverImageUrls[0] : `http://localhost:3001${course.coverImageUrls[0]}`)
                                    : ""
                                }
                                fallback=""
                            />
                        </Col>
                        <Col span={16}>
                            <p><strong>课程名称：</strong>{course.name}</p>
                            <p><strong>讲师：</strong>{course.teacherName}</p>
                            <p><strong>价格：</strong>¥{(course.price / 100).toFixed(2)}</p>
                            <p><strong>描述：</strong>{course.description}</p>
                            <p><strong>视频数量：</strong>{course.videoResources?.length || 0}</p>
                            <p><strong>图片数量：</strong>{course.imageResources?.length || 0}</p>
                            <p><strong>上传时间：</strong>{new Date(course.createdAt).toLocaleString()}</p>
                        </Col>
                    </Row>
                </div>
            ),
        });
    };

    // 播放课程
    const handlePlayCourse = (course) => {
        if (course.videoResources && course.videoResources.length > 0) {
            const videoUrl = course.videoResources[0].videoUrl;
            window.open(`http://localhost:3001${videoUrl}`, '_blank');
        } else {
            message.warning('该课程暂无视频资源');
        }
    };

    // 处理表格分页
    const handleTableChange = (pagination) => {
        fetchCourses(pagination.current, searchText);
    };

    // 处理搜索
    const handleSearch = (value) => {
        setSearchText(value);
        fetchCourses(1, value);
    };

    // 重置表单
    const handleReset = () => {
        form.resetFields();
        setFormValues({
            name: '',
            description: '',
            price: 0,
            coverImageUrls: [],
            videoUrls: [],
            imageUrls: [],
            teacherId: '',
            teacherName: ''
        });
        setUploadedVideos([]);
        setUploadedImages([]);
        setCoverImages([]);
    };

    // 跳转到AI教育助手页面
    const handleGoToAI = () => {
        window.open('/homed', '_blank');
    };

    return (
        <div>
            <Card title="课程筛选" bordered={false} className={styles.filterCard}>
                <div className={styles.filterSection}>
                    <div className={styles.filterItem}>
                        <Search
                            placeholder="请输入课程名称或关键词"
                            style={{ width: 300 }}
                            onSearch={handleSearch}
                            allowClear
                        />
                    </div>
                    <div className={styles.filterItem}>
                        <ActionPermissionGuard action="add" userId={JSON.parse(localStorage.getItem('currentUser') || '{}').id}>
                            <Button 
                                type="primary" 
                                icon={<PlusOutlined />}
                                onClick={() => setIsModalVisible(true)}
                            >
                                添加课程
                            </Button>
                        </ActionPermissionGuard>
                    </div>
                    <div className={styles.filterItem}>
                        <Tooltip title="使用AI智能生成课程大纲、教案、考试题目等教育文档" placement="bottom">
                            <Button 
                                type="default" 
                                icon={<RobotOutlined />}
                                onClick={handleGoToAI}
                                className={styles.aiButton}
                            >
                                🤖 AI教育助手
                            </Button>
                        </Tooltip>
                    </div>
                </div>
            </Card>

            <Card title="课程列表" bordered={false} className={styles.listCard}>
                <Table
                    columns={columns}
                    dataSource={courses}
                    rowKey="_id"
                    loading={loading}
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
                        itemRender: (page, type, originalElement) => {
                            if (type === 'prev') return <LeftOutlined />;
                            if (type === 'next') return <RightOutlined />;
                            return originalElement;
                        }
                    }}
                    onChange={handleTableChange}
                    scroll={{ x: 1200 }}
                    className={styles.table}
                />
            </Card>

            {/* 添加课程模态框 */}
            <Modal
                title="添加课程 - 支持大文件上传"
                visible={isModalVisible}
                onOk={handleAddCourse}
                onCancel={() => {
                    setIsModalVisible(false);
                    // 重置表单和状态
                    form.resetFields();
                    setFormValues({
                        name: '',
                        description: '',
                        price: 0,
                        coverImageUrls: [],
                        videoUrls: [],
                        imageUrls: [],
                        teacherId: '',
                        teacherName: ''
                    });
                    setUploadedVideos([]);
                    setUploadedImages([]);
                    setCoverImages([]);
                }}
                width={900}
                okText="添加"
                cancelText="取消"
                confirmLoading={uploading}
            >
                <Form
                form={form}
                layout="vertical"
                onFinish={handleAddCourse}
                initialValues={formValues}
                >
                <Row gutter={16}>
                    <Col span={12}>
                    <Form.Item
                        label="课程名称"
                        name="name"
                        rules={[{ required: true, message: '请输入课程名称' }]}
                    >
                        <Input 
                        placeholder="请输入课程名称" 
                        value={formValues.name}
                        onChange={(e) => setFormValues({...formValues, name: e.target.value})}
                        />
                    </Form.Item>
                    </Col>
                    <Col span={12}>
                    <Form.Item
                        label="课程价格（分）"
                        name="price"
                        rules={[{ required: true, message: '请输入课程价格' }]}
                    >
                        <Input 
                        type="number" 
                        placeholder="请输入价格（分）" 
                        min={0}
                        value={formValues.price}
                        onChange={(e) => setFormValues({...formValues, price: e.target.value})}
                        />
                    </Form.Item>
                    </Col>
                </Row>

                <Form.Item
                    label="课程描述"
                    name="description"
                >
                    <TextArea 
                    rows={4} 
                    placeholder="请输入课程描述"
                    value={formValues.description}
                    onChange={(e) => setFormValues({...formValues, description: e.target.value})}
                    />
                </Form.Item>

                <Row gutter={16}>
                    <Col span={12}>
                    <Form.Item
                        label="选择讲师"
                        name="teacherId"
                        rules={[{ required: true, message: '请选择讲师' }]}
                    >
                        <Select
                        placeholder="请选择讲师"
                        value={formValues.teacherId}
                        onChange={(value) => {
                            const teacher = teachers.find(t => t._id === value);
                            setFormValues({
                            ...formValues,
                            teacherId: value,
                            teacherName: teacher?.name || ''
                            });
                        }}
                        >
                        {teachers.map(teacher => (
                            <Option key={teacher._id} value={teacher._id}>
                            {teacher.name}
                            </Option>
                        ))}
                        </Select>
                    </Form.Item>
                    </Col>
                    <Col span={12}>
                    <Form.Item label="封面图片">
                        <Upload.Dragger
                        beforeUpload={(file) => {
                            handleCoverImageUpload(file);
                            return false;
                        }}
                        showUploadList={false}
                        accept="image/*"
                        multiple={true}
                        >
                        <p className="ant-upload-drag-icon">
                            <FileImageOutlined />
                        </p>
                        <p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
                        <p className="ant-upload-hint">
                            支持多个图片，单个文件最大 10MB
                        </p>
                        </Upload.Dragger>
                        {coverImages.length > 0 && (
                        <div style={{ marginTop: 8 }}>
                            <Text>已上传封面图片：</Text>
                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
                                {coverImages.map((image, index) => (
                                    <div key={index} style={{ position: 'relative' }}>
                                        <Image
                                            width={100}
                                            height={100}
                                            src={image.url.startsWith('http') ? image.url : `http://localhost:3001${image.url}`}
                                            style={{ objectFit: 'cover' }}
                                        />
                                        <Button
                                            type="text"
                                            size="small"
                                            icon={<DeleteOutlined />}
                                            style={{
                                                position: 'absolute',
                                                top: 0,
                                                right: 0,
                                                background: 'rgba(255, 0, 0, 0.7)',
                                                color: 'white',
                                                border: 'none'
                                            }}
                                            onClick={() => {
                                                setCoverImages(prev => prev.filter((_, i) => i !== index));
                                                setFormValues(prev => ({
                                                    ...prev,
                                                    coverImageUrls: prev.coverImageUrls?.filter((_, i) => i !== index) || []
                                                }));
                                            }}
                                        />
                                    </div>
                                ))}
                            </div>
                        </div>
                        )}
                    </Form.Item>
                    </Col>
                </Row>

                <Divider>课程资源</Divider>
                
                <Form.Item label="上传视频/文档">
                    <Upload.Dragger
                    beforeUpload={(file) => {
                        handleFileUpload(file);
                        return false;
                    }}
                    showUploadList={false}
                    accept="video/*,.ppt,.pptx,.doc,.docx,.pdf,.xls,.xlsx,.txt"
                    multiple={true}
                    >
                    <p className="ant-upload-drag-icon">
                        <CloudUploadOutlined />
                    </p>
                    <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                    <p className="ant-upload-hint">
                        支持视频文件和文档文件（PPT、Word、PDF、Excel、TXT等），单个文件最大 500MB
                    </p>
                    </Upload.Dragger>
                    
                    {/* 上传进度显示 */}
                    {Object.keys(chunkUploadProgress).length > 0 && (
                        <div style={{ marginTop: 16 }}>
                            <Alert
                                message="文件上传中"
                                description={
                                    <div>
                                        {Object.entries(chunkUploadProgress).map(([fileId, progress]) => (
                                            <div key={fileId} style={{ marginBottom: 8 }}>
                                                <Text>{fileId}</Text>
                                                <Progress 
                                                    percent={progress.percentage} 
                                                    size="small"
                                                    status="active"
                                                />
                                            </div>
                                        ))}
                                    </div>
                                }
                                type="info"
                                showIcon
                            />
                        </div>
                    )}

                    {/* 已上传视频显示 */}
                    {uploadedVideos.length > 0 && (
                    <div style={{ marginTop: 16 }}>
                        <Text strong>已上传视频：</Text>
                        <div style={{ marginTop: 8 }}>
                        {uploadedVideos.map((video, index) => (
                        <Tag 
                            key={index} 
                            icon={video.icon || <VideoCameraOutlined />}
                            color="blue"
                            closable 
                            onClose={() => {
                                setUploadedVideos(prev => prev.filter((_, i) => i !== index));
                                setFormValues(prev => ({
                                ...prev,
                                videoUrls: prev.videoUrls.filter((_, i) => i !== index)
                                }));
                            }}
                            style={{ marginBottom: 8 }}
                        >
                            {video.originalName || video.filename}
                        </Tag>
                        ))}
                        </div>
                    </div>
                    )}

                    {/* 已上传文档显示 */}
                    {uploadedFiles.length > 0 && (
                    <div style={{ marginTop: 16 }}>
                        <Text strong>已上传文档：</Text>
                        <div style={{ marginTop: 8 }}>
                        {uploadedFiles.map((file, index) => (
                        <Tag 
                            key={index} 
                            icon={file.icon || <FileTextOutlined />}
                            color="green"
                            closable 
                            onClose={() => {
                                setUploadedFiles(prev => prev.filter((_, i) => i !== index));
                                setFormValues(prev => ({
                                ...prev,
                                fileUrls: prev.fileUrls.filter((_, i) => i !== index)
                                }));
                            }}
                            style={{ marginBottom: 8 }}
                        >
                            {file.originalName || file.filename} ({file.category})
                        </Tag>
                        ))}
                        </div>
                    </div>
                    )}
                </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}
